package com.qky.note.part11javatrans;

import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CodePointCharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.RuleNode;

import java.util.Locale;

public class JavaCustomVisitor extends JavaParserBaseVisitor<String> {
    public static void main(String[] args) {
        String aa = "haha";
        CodePointCharStream input = CharStreams.fromString("public class test {\n" +
                "    public static void main(String[] args) {\n" +
                "        String aa = \"haha\";\n" +
                "    }\n" +
                "}");
        JavaLexer lexer = new JavaLexer(input);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        JavaParser parser = new JavaParser(tokens);
        ParseTree tree = parser.compilationUnit(); // parse
//
        JavaCustomVisitor eval = new JavaCustomVisitor();
        String result = eval.visit(tree);
        System.out.println(result);
    }

    @Override
    public String visitChildren(RuleNode node) {
//        System.out.println(node.getRuleContext().getRuleIndex() + ":" + JavaParser.ruleNames[node.getRuleContext().getRuleIndex()]);
//        System.out.println(node.getText());
        StringBuilder result = new StringBuilder();
        int n = node.getChildCount();

        for (int i = 0; i < n; ++i) {
            ParseTree c = node.getChild(i);
            String childResult = c.accept(this);
            if (childResult == null) {
                childResult = c.getText();
            }
            result.append(childResult);
        }

        return result.toString();
    }


    @Override
    public String visitLocalVariableDeclaration(JavaParser.LocalVariableDeclarationContext ctx) {

        ParseTree first = ctx.getChild(0);
        System.out.println(first.getChildCount());
        System.out.println(first.getChild(0).getChildCount());
        System.out.println(first.getChild(0).getText());

        ParseTree second = ctx.getChild(1);
        System.out.println(second.getChild(0).getChild(0).getText());
        System.out.println(second.getChild(0).getChild(2).getText());
        visitChildren(ctx);

        String id = first.getChild(0).getText().toLowerCase();
        String name = second.getChild(0).getChild(0).getText();
        String value = second.getChild(0).getChild(2).getText();

        System.out.println("const " + name + ":" + id + " = " + value);
        return "const " + name + " : " + id + " = " + value;
    }
}
